/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package avl.sv.client.source;

import avl.sv.server.training.Training;
import avl.sv.shared.Solution;
import avl.sv.shared.XML.SolutionXML_Parser;
import avl.sv.shared.sources.SolutionSource;
import ij.gui.MessageDialog;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;

/**
 *
 * @author benbryan
 */
public class SolutionSourcePort extends SolutionSource  {
    private final Training port;
    
    public SolutionSourcePort(Training port, String name, int id) {
        super(name, id);
        this.port = port;
    }

    public long getVersion(){
        return port.getSolutionVersion(getId());
    }
    
    @Override
    public String setSolution(String xml) {
        return port.setSolution( getId(), xml);
    }

    @Override
    public Solution getSolution() {
        try {
            String xml = port.getSolution( getId());
            if ((xml == null) || (xml.equals(""))) {
                return new Solution(getName());
            }
            if (xml.contains("error:")){
                new MessageDialog(null, "Error getting solution from server", xml ).setVisible(true);
                return null;
            }            
            SolutionXML_Parser parser = new SolutionXML_Parser();
            Solution solution = parser.parse(xml);
            return solution;
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            Logger.getLogger(SolutionSource.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public boolean exists(Training port, String name) {
        return port.getSolution(getId()) != null;
    }

    @Override
    public String delete() {
        return port.deleteSolution( getId());
    }
    
}
